package net.wicp.tams.commons.binlog.event.rows;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.ByteUtil;
import net.wicp.tams.commons.binlog.bean.EventBean;
import net.wicp.tams.commons.binlog.bean.TableMapBean;
import net.wicp.tams.commons.binlog.constant.ColumnType;
import net.wicp.tams.commons.binlog.event.AbsEvent;
import net.wicp.tams.commons.callback.ICol;
import net.wicp.tams.commons.io.UnsignedLong;

@Slf4j
public abstract class RowsEvent extends AbsEvent {
	protected int version = 1;// 只支持版本为1/2的事件,默认为1
	protected long tableId;
	protected int flags;
	protected String extraData;
	protected UnsignedLong columnCount;
	private byte[] columnsPresentBitmap1;
	protected TableMapBean table;

	public RowsEvent(EventBean event) {
		super(event);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public final Result parseBody() {
		rowlog();
		int postHeadLength = event.getHead().getEventType().getPostHeaderLength();
		if (postHeadLength == -1) {
			return Result.getError("没有初始化，FormatDescription事件必须第一个读.");
		}
		if (postHeadLength == 6) {
			tableId = ByteUtil.readLongL(readSubByte(4));
		} else {
			tableId = ByteUtil.readLongL(readSubByte(6));
		}
		flags = ByteUtil.readIntL(readSubByte(2));
		if (version == 2) {
			int extraDataLength = ByteUtil.readIntL(readSubByte(2));
			extraData = ByteUtil.readString(readSubByte(extraDataLength - 2));
		}

		// body
		columnCount = readUnsignedLong();
		int presentBitmap1Length = (columnCount.intValue() + 7) / 8;
		columnsPresentBitmap1 = readSubByte(presentBitmap1Length);
		parseUpdate();
		// rows:
		rowlog();
		int presentBitmapNum = ByteUtil.byteshas1(columnsPresentBitmap1);
		presentBitmapNum = presentBitmapNum > columnCount.intValue() ? columnCount.intValue() : presentBitmapNum;
		byte[] nulbitmap = readSubByte((presentBitmapNum + 7) / 8);
		table = TableMapBean.tbs.get(tableId);

		// 1、判断columnsPresentBitmap1 为1
		int PresentIs1 = -1;
		for (int i = 0; i < table.getColumnCount(); i++) {
			if ((columnsPresentBitmap1[i / 8] & 0x01 << i % 8) != 0x00) {
				PresentIs1++;
				// 2、判断nulbitmap是否有
				if ((nulbitmap[PresentIs1 / 8] & 0x01 << (PresentIs1 % 8)) != 0x00) {
					System.out.println("是空值");
				} else {// 0 表示不是空值
					ColumnType colType = table.getColumnTypes()[i];
					ICol col = paseCol(colType, table.getMetaDefs()[i]);
					log.info("值【{}】", col.toClient());
				}

			} else {// 没有持有

			}
		}
		parseUpdateForRows();
		return null;
	}

	public abstract void parseUpdate();

	public abstract void parseUpdateForRows();

}
